# -*- coding=
import json

import pandas as pd
import joblib
import os

def get_result(new_data:pd.DataFrame):
    working_directory = 'all_model_results/Decisiontree'
    # new_data = pd.DataFrame({
    #     "Transaction_ID": ["TXN_33553"],
    #     "User_ID": ["USER_1834"],
    #     "Transaction_Amount": [39.79],
    #     "Transaction_Type": ["POS"],
    #     "Timestamp": ["2023/8/14 19:30"],
    #     "Account_Balance": [93213.17],
    #     "Device_Type": ["Laptop"],
    #     "Location": ["Sydney"],
    #     "Merchant_Category": ["Travel"],
    #     "IP_Address_Flag": [0],
    #     "Previous_Fraudulent_Activity": [0],
    #     "Daily_Transaction_Count": [7],
    #     "Avg_Transaction_Amount_7d": [437.63],
    #     "Failed_Transaction_Count_7d": [3],
    #     "Card_Type": ["Amex"],
    #     "Card_Age": [65],
    #     "Transaction_Distance": [883.17],
    #     "Authentication_Method": ["Biometric"],
    #     "Risk_Score": [0.8494],
    #     "Is_Weekend": [0],
    #     "Fraud_Label": [0]
    # })

    # Preprocess new data
    # Drop unnecessary columns
    for col in ['Transaction_ID', 'User_ID']:
        if col in new_data.columns:
            new_data.drop(columns=col, inplace=True)

    # Process Timestamp
    new_data['Timestamp'] = pd.to_datetime(new_data['Timestamp'], errors='coerce')
    new_data['Hour'] = new_data['Timestamp'].dt.hour
    new_data['DayOfWeek'] = new_data['Timestamp'].dt.dayofweek
    new_data.drop(columns=['Timestamp'], inplace=True)
    categorical_columns = ['Authentication_Method', 'Device_Type', 'Merchant_Category', 'Transaction_Type', 'Location', 'Card_Type', 'Fraud_Label']
    numerical_columns=['Transaction_Amount', 'Account_Balance', 'IP_Address_Flag', 'Previous_Fraudulent_Activity', 'Daily_Transaction_Count', 'Avg_Transaction_Amount_7d', 'Failed_Transaction_Count_7d', 'Card_Age', 'Transaction_Distance', 'Risk_Score', 'Is_Weekend', 'Hour', 'DayOfWeek']
    # Encode categorical variables
    for col in categorical_columns:
        encoder_path = os.path.join(working_directory, f'{col}_encoder.joblib')
        encoder = joblib.load(encoder_path)
        new_data[col] = new_data[col].astype(str)
        new_data[col] = encoder.transform(new_data[col])

    # Standardize Numerical Features
    scaler_path = os.path.join(working_directory,'scaler.joblib')
    scaler = joblib.load(scaler_path)
    new_data[numerical_columns] = scaler.transform(new_data[numerical_columns])

    # Remove target variable if present
    if 'Fraud_Label' in new_data.columns:
        new_data.drop(columns=['Fraud_Label'], inplace=True)

    # Load the model
    model_path = os.path.join(working_directory, f'{working_directory}_model.joblib')
    xgb_model = joblib.load(model_path)

    # Make prediction
    new_pred = xgb_model.predict(new_data)
    new_prob = xgb_model.predict_proba(new_data)[:, 1]
    return new_pred,new_prob
def get_saved_results():
    base_working_directory = 'all_model_results'
    all_results_path = os.path.join(base_working_directory, 'all_models_metrics.json')
    if os.path.exists(all_results_path):
        with open(all_results_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    else:
        print(f"未找到结果文件: {all_results_path}")
        return None
